"""
滑动窗口法 - 详细演示
用于理解如何找到最长不重复子串
"""


def lengthOfLongestSubstring_demo(s: str) -> int:
    """
    滑动窗口法详细演示版本
    """
    if not s:
        return 0

    # 核心数据结构
    char_index = {}  # 字典：记录每个字符最后出现的索引位置
    max_length = 0  # 记录找到的最大长度
    left = 0  # 窗口左边界

    print(f"\n{'='*80}")
    print(f"字符串: '{s}'")
    print(f"目标: 找到最长的不重复子串")
    print(f"{'='*80}\n")

    # right 指针遍历整个字符串
    for right, char in enumerate(s):
        print(f"\n{'─'*80}")
        print(f"步骤 {right + 1}: 检查字符 '{char}' (索引 {right})")
        print(f"{'─'*80}")

        # 可视化当前字符串和窗口位置
        print(f"\n字符串:  ", end="")
        for i, c in enumerate(s):
            if i == right:
                print(f"[{c}]", end=" ")
            else:
                print(f" {c} ", end=" ")
        print()

        print(f"索引:    ", end="")
        for i in range(len(s)):
            print(f" {i}  ", end="")
        print()

        # 显示当前窗口范围
        print(f"窗口:    ", end="")
        for i in range(len(s)):
            if i == left and i == right:
                print(" ⇅  ", end="")  # left 和 right 重合
            elif i == left:
                print(" ⇑  ", end="")  # left 位置
            elif i == right:
                print(" ⇓  ", end="")  # right 位置
            elif left < i < right:
                print(" │  ", end="")  # 窗口内
            else:
                print("    ", end="")
        print()

        # 检查是否重复
        is_duplicate = char in char_index and char_index[char] >= left

        if is_duplicate:
            old_left = left
            old_pos = char_index[char]
            # 移动左边界到重复字符的下一个位置
            left = char_index[char] + 1

            print(f"\n⚠️  发现重复字符 '{char}'!")
            print(f"   之前出现在索引 {old_pos}（在当前窗口内）")
            print(f"   窗口左边界移动: {old_left} → {left}")
            print(f"   移除了字符: {s[old_left:left]}")
        else:
            print(f"\n✓  字符 '{char}' 是新字符（未在窗口内出现）")

        # 更新字符的最新位置
        char_index[char] = right

        # 计算当前窗口
        current_window = s[left : right + 1]
        current_length = right - left + 1

        print(f"\n当前状态:")
        print(f"   窗口范围: [{left}, {right}]")
        print(f"   窗口内容: '{current_window}'")
        print(f"   窗口长度: {current_length}")
        print(f"   字符位置字典: {dict(sorted(char_index.items()))}")

        # 更新最大长度
        if current_length > max_length:
            print(f"\n🎉 更新最大长度: {max_length} → {current_length}")
            max_length = current_length
        else:
            print(f"   当前最大长度仍为: {max_length}")

    print(f"\n{'='*80}")
    print(f"最终结果: 最长不重复子串长度 = {max_length}")
    print(f"{'='*80}\n")

    return max_length


# 测试不同的例子
if __name__ == "__main__":
    test_cases = [
        "abcabcbb",  # 答案: 3 (abc)
        "bbbbb",  # 答案: 1 (b)
        "pwwkew",  # 答案: 3 (wke)
        "dvdf",  # 答案: 3 (vdf)
    ]

    for test_str in test_cases:
        result = lengthOfLongestSubstring_demo(test_str)
        print(f"\n输入: '{test_str}' → 输出: {result}\n")
        input("按 Enter 继续下一个示例...")
        print("\n" * 2)
